#pragma once
#include <iostream>
#include <string>
#include <functional>
#include "InetAddr.hpp"
#include "Log.hpp"
using namespace log_ns;


#define ListenSock 0
#define NormalSock 1

class Connection;
class Reactor;
using handler_t = std::function<void(Connection *con)>;

// 一个连接，在之后的使用中，没有 sockfd，只有连接
class Connection
{
public:
    Connection(int fd) : _sockfd(fd)
    {
    }
    int Sockfd()
    {
        return _sockfd;
    }

    void SetEvent(uint32_t ev)
    {
        _event = ev;
    }
    uint32_t Events()
    {
        return _event;
    }

    void SetType(int type)
    {
        _type = type;
    }
    int Type()
    {
        return _type;
    }

    void SetAddr(InetAddr &addr)
    {
        _addr = addr;
    }

    void SetReactor(Reactor *r)
    {
        _R = r;
    }

    void AppendInbuffer(const std::string &in)
    {
        _inbuffer += in;
    }

    void AppendOutbuffer(const std::string &in)
    {
        _outbuffer += in;
    }

    void DiscardOutbuffer(int n)
    {
        // abcdef，发送了3，变成了def
        _outbuffer.erase(0, n);
    }

    std::string& Inbuffer()
    {
        return _inbuffer;
    }
    
    std::string &Outbuffer()
    {
        return _outbuffer;
    }
    
    void Close()
    {
        close(_sockfd);
    }

    void HandlerRegister(handler_t receive, handler_t sender, handler_t excepter)
    {
        _handler_receiver = receive;
        _handler_sender = sender;
        _handler_excepter = excepter;
    }
private:
    // 一个最基本的字段
    int _sockfd;
    uint32_t _event;
    int _type; // 连接类型，分为 listensock 和 普通sock
    InetAddr _addr; // 网络地址信息，ip端口

    // 缓冲区
    std::string _inbuffer;
    std::string _outbuffer;

public:
    handler_t _handler_receiver; // 处理读取
    handler_t _handler_sender;   // 处理写入
    handler_t _handler_excepter; // 处理异常

    Reactor *_R; // 回指向管理自己的Reactor
};